/*
* Copyright (c) 2016 . All Rights Reserved.
*/
package com.cgmnx.admin.service.rbac.impl;

import com.cgmnx.admin.common.exception.ServiceException;
import com.cgmnx.admin.dao.entity.rbac.RoleResourceRelationEntity;
import com.cgmnx.admin.dao.mapper.rbac.RoleResourceRelationMapper;
import com.cgmnx.admin.service.rbac.RoleResourceRelationService;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author: created  Date: 16/12/14 Time: 下午4:07
 * @version: 1.0
 */
@Slf4j
@Service
public class RoleResourceRelationServiceImpl implements RoleResourceRelationService {

//    @Autowired
    private RoleResourceRelationMapper roleResourceRelationMapper;


    @Override
    public int deleteByRoleId(Integer roleId) {
        return roleResourceRelationMapper.deleteByRoleId(roleId);
    }

    @Override
    public int allocation(final Integer roleId, Set<Integer> resourceIdList, final String userId) {

        if (roleId == null || CollectionUtils.isEmpty(resourceIdList)) {
            throw new ServiceException("角色id或者资源列表为空");
        }

        List<RoleResourceRelationEntity> relationEntityList = FluentIterable.from(resourceIdList).transform(new Function<Integer, RoleResourceRelationEntity>() {
            @Override
            public RoleResourceRelationEntity apply(Integer input) {
                if (input == null) {
                    return null;
                }

                RoleResourceRelationEntity relationEntity = new RoleResourceRelationEntity();
                relationEntity.setRoleId(roleId);
                relationEntity.setResourceId(input);
                relationEntity.setCreateUser(userId);
                relationEntity.setUpdateUser(userId);
                return relationEntity;
            }
        }).toList();

        return roleResourceRelationMapper.saveAll(relationEntityList);
    }


    @Override
    public List<RoleResourceRelationEntity> query(Integer resourceId) {
        return roleResourceRelationMapper.query(resourceId);
    }


    @Override
    public Integer count(Integer roleId) {
        return roleResourceRelationMapper.count(roleId);
    }


}